<template>
	<view class="scrool-page">
		<view class="list-cont">
			<scroll-view class="scrool-more" style="height: 100%" scroll-y="true" scroll-with-animation="true">
				<view v-for="(item,index) in detailList" :key="index">
					<uni-card :title="'序号:'+(index+1)" v-if='item.isChecked' style='background-color: darkgrey;'>
						<text class="uni-body">物料编码：{{ item.itemCode }}</text><br>
						<text class="uni-body">数量：{{ item.codeEqualQty }}</text><br>
						<text class="uni-body">箱号：{{ item.boxCode }}</text><br>
					</uni-card>

					<uni-card :title="'序号:'+(index+1)" v-else>
						<text class="uni-body">物料编码：{{ item.itemCode }}</text><br>
						<text class="uni-body">数量：{{ item.codeEqualQty }}</text><br>
						<text class="uni-body">箱号：{{ item.boxCode }}</text><br>
					</uni-card>
				</view>
			</scroll-view>
		</view>

		<view class="footer">
			<button type="default" @click="submit">确认</button>
		</view>

		<uni-popup ref="dataDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true"
				content="检测到有缓存数据是否加载？" @confirm="dataConfirm" @close="dataClose">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getToken
	} from '@/utils/auth'
	import common from '../../pages/common/common.js'
	var main, receiver, filter;
	var ScanDeviceClass = plus.android.importClass("android.device.ScanDevice");
	var scanDevice;
	export default {
		data() {
			return {
				trojanCode: '',
				content: '',
				detailList: [],
				boxCode: '',
				mseeageContent: '',
				baseUrl: getApp().globalData.config.baseUrl,
				userName: this.$store.state.user.name,
				orgId: getApp().globalData.config.orgId,
				soDocno: '', //销售订单
				sn: '', //拖序号
				sn1: '', //托序号
				identification: '',
				ip: getApp().globalData.config.ip,
				port: getApp().globalData.config.port,
				custPoNo: '',
				sumbitFlag: true,
				total: 0,
				scanNum: 0,
				invoiceNo: '', //发票号

				qrcodeContent: '',
				printType: '',
				reprint: '',

				packageId: '',
				markstemplate: ''
			}
		},


		onBackPress(options) {
			var that = this;
			if (options.from === 'navigateBack') {
				return false;
			}
			var count = 0;
			for (var i = 0; i < that.detailList.length; i++) {
				if (that.detailList[i].isChecked) {
					count = count + 1;
				}
			}
			if (that.sumbitFlag && count > 0) {
				try {
					uni.setStorageSync(that.trojanCode, that.detailList);
					uni.setStorageSync(that.trojanCode + "soDocno", that.soDocno);
					uni.setStorageSync(that.trojanCode + "sn", that.sn);
					uni.setStorageSync(that.trojanCode + "identification", that.identification);
					uni.setStorageSync(that.trojanCode + "custPoNo", that.custPoNo);
					//uni.setStorageSync('product_recpt_barcode', that.barcodeIdList);
				} catch (e) {
					console.log(e.message);
				}
			}
			//that.unregisterScan();
			//player.stop();
			uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
				delta: 1
			});
			return true;
		},

		mounted() {
			this.orgId = uni.getStorageSync('orgId');
			var ipValue = uni.getStorageSync('ip');
			if (ipValue != null && ipValue != '') {
				this.ip = ipValue;
			}
			var portValue = uni.getStorageSync('port');
			if (portValue != null && portValue != '') {
				this.port = portValue;
			}
		},

		onShow() {
			scanDevice = new ScanDeviceClass();
			scanDevice.openScan(); // 打开扫描
			scanDevice.setOutScanMode(0); // 扫描模式				
			this.initScan();
			this.registerScan();
		},

		onHide: function() {
			this.unregisterScan();
		},

		destroyed: function() {
			this.unregisterScan();
		},

		methods: {
			initScan() {
				let _this = this;
				main = plus.android.runtimeMainActivity(); //获取activity  
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				filter = new IntentFilter();
				filter.addAction("scan.rcv.message"); // 换你的广播动作  
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let code = intent.getByteArrayExtra('barocode');
						let codeStr = common.utf8ByteToUnicodeStr(code);
						scanDevice.stopScan(); // 停止扫描	
						var result = common.scanCode(codeStr);
						if (result[0] == "T") {
							_this.trojanCode = result[1];
							_this.checkFinished(codeStr);
						} else if (result[0] == "C") {
							_this.scan(result[1]);
						} else {
							uni.showToast({
								title: '请正确扫描箱号',
								icon: 'none',
								duration: 3000
							});
						}
					}
				});
			},

			registerScan() {
				main.registerReceiver(receiver, filter);
			},

			unregisterScan() {
				main.unregisterReceiver(receiver);
			},

			//查询此托是否已完成
			checkFinished(codeStr) {
				//显示加载框
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				var that = this;
				uni.request({
					url: this.baseUrl + '/system/unpline/pallet',
					data: {
						orgId: that.orgId,
						userName: that.userName,
						cipherCode: that.trojanCode,
						type: 'check'
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						if (res.data.code == '200' || res.data.code == 200) {
							that.queryCustmerType();
						} else if (res.data.code == '201' || res.data.code == 201) {
							uni.showModal({
								title: '提示',
								content: '此' + codeStr + '托未完成，不允许校验，请查看组托任务。',
								success: function(res) {
									if (res.confirm) {
										return;
									} else {
										return;
									}
								}
							})
						} else if (res.data.code == '50000') { //20240205判断组托计划锁定
							uni.showToast({
								duration: 4000,
								icon: 'none',
								title: '该组托计划正在做变更已被锁定,不允许操作!'
							})
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
							return;
						}

					},
				})
			},

			queryCustmerType() {
				//显示加载框
				var that = this;
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				uni.request({
					url: that.baseUrl + '/system/record/category',
					data: {
						orgId: that.orgId,
						userName: that.userName,
						cipherCode: that.trojanCode,
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						if (res.data.code == '200' || res.data.code == 200) {
							if (res.data.msg == '1') {
								//that.unregisterScan();
								uni.redirectTo({
									url: '/pages/wm_package/wm_package_check_one?trojanCode=' + that
										.trojanCode
								})
							} else if (res.data.msg == '3') {
								//that.unregisterScan();
								uni.redirectTo({
									url: '/pages/wm_package/wm_package_check_three?trojanCode=' + that
										.trojanCode
								})
							} else {
								const value = uni.getStorageSync(that.trojanCode);
								if (value.length > 0) {
									that.$refs.dataDialog.open();
								} else {
									that.query(that.trojanCode);
								}
							}
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}

					},
				})
			},

			query(codeStr) {
				//显示加载框
				console.log("2")
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				uni.request({
					url: this.baseUrl + '/system/record/box',
					data: {
						qrcodeContent: codeStr,
						orgId: this.orgId
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						console.log(res.data);
						if (res.data.code == '200' || res.data.code == 200) {
							this.detailList = res.data.data.returnList;
							this.soDocno = res.data.data.soDocno;
							this.sn = res.data.data.attr5;
							this.packageId = res.data.data.packageId;
							this.sn1 = res.data.data.attr6;
							this.invoiceNo = res.data.data.invoiceNo;
							this.identification = res.data.data.identification;
							this.custPoNo = res.data.data.custPoNo;

							this.qrcodeContent = res.data.data.qrcodeContent;
							this.printType = res.data.data.printType;
							this.reprint = res.data.data.reprint;

							this.total = this.detailList.length;
							this.countNum();
							var count = 0;
							for (var i = 0; i < this.detailList.length; i++) {
								if (this.detailList[i].isChecked) {
									count = count + 1;
								}
							}
							this.scanNum = count;
							console.log(this.scanNum)
							console.log(codeStr)
							uni.setNavigationBarTitle({
								title: codeStr + '(' + this.scanNum + '/' + this.total + ')'
							});
							this.getcustom()
						} else {
							this.detailList = [];
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}

					},
				})
			},
			getcustom() {
				console.log(this.sn1)
				uni.request({
					url: this.baseUrl + '/system/templates/getMarksAndBoxCode',
					data: {

						orgId: this.orgId,
						packageId: this.packageId,
						panelCode: this.sn1

					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						console.log(res)
						this.markstemplate = res.data.data[0].markstemplate

					},
				})
			},

			countNum(codeStr) {
				var count = 0;
				for (var i = 0; i < this.detailList.length; i++) {
					if (this.detailList[i].isChecked) {
						count = count + 1;
					}
				}
				this.scanNum = count;
				console.log(this.scanNum)
				uni.setNavigationBarTitle({
					title: this.trojanCode + '(' + this.scanNum + '/' + this.total + ')'
				});
			},

			scan(codeStr) {
				var that = this;
				console.log(codeStr)
				that.boxCode = codeStr;
				var data = '';
				var flag = 0;
				console.log(that.detailList)
				for (var i = 0; i < that.detailList.length; i++) {
					data = that.detailList[i];
					if (data.boxCode == codeStr) {
						if (data.isChecked) {
							flag = 1;
						} else {
							flag = 2;
						}
						break;
					}
				}
				if (flag == 0) {
					uni.showToast({
						title: '此箱不属于该托，请检查',
						icon: 'none',
						duration: 3000
					});
					return;
				} else if (flag == 1) {
					uni.showToast({
						title: '此箱已扫描',
						icon: 'none',
						duration: 3000
					});
					return;
				} else {
					data.isChecked = true;
					that.prompt();
					that.countNum();
					// that.scanNum = that.scanNum + 1;
					// console.log(that.scanNum)
					// uni.setNavigationBarTitle({
					// 	title: that.trojanCode + '(' + that.scanNum + '/' + that.total + ')'
					// });
				}
				//this.dialogConfirm(this.detailList);
				//this.content = '箱号：' +codeStr+"\n";
				//this.$refs.alertDialog.open();
			},

			submit() {
				var that = this;
				//显示加载框
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				var count = 0;
				for (var i = 0; i < that.detailList.length; i++) {
					if (that.detailList[i].isChecked) {
						count = count + 1;
					}
				}
				if (count == that.detailList.length) {
					uni.request({
						url: that.baseUrl + '/system/record/qrcodeContent',
						data: {
							orgId: that.orgId,
							qrcodeContent: that.trojanCode,
							userName: that.userName
						},
						method: 'POST',
						header: {
							'authorization': getToken()
						},
						dataType: 'json',
						success: (res) => {
							if (res.data.code == '200' || res.data.code == 200 || res.data.code == '201' || res
								.data.code == 201) {
								//隐藏加载框
								uni.hideLoading();
								that.sumbitFlag = false;
								that.print();
								var json = JSON.parse(res.data.data);
								var unFinsh = json.unFinsh;
								if (unFinsh == 0 || unFinsh == "0") {
									var packageId = json.packageId;
									that.finished(packageId);
								} else {
									//隐藏加载框
									uni.hideLoading();
									uni.showToast({
										title: res.data.msg,
										icon: 'none',
										duration: 5000
									});
									that.removeStorageSync();
									//player.stop();
									setTimeout(function() {
										uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
											delta: 1
										});
									}, 2000);
								}
							} else if (res.data.code == '201' || res.data.code == 201) {
								that.sumbitFlag = false;
								var json = JSON.parse(res.data.data);
								var unFinsh = json.unFinsh;
								that.print();
								if (unFinsh == 0 || unFinsh == "0") {
									var packageId = json.packageId;
									that.finished(packageId);
								} else {
									//隐藏加载框
									uni.hideLoading();
									uni.showToast({
										title: res.data.msg,
										icon: 'none',
										duration: 5000
									});
									that.removeStorageSync();
									//player.stop();
									setTimeout(function() {
										uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
											delta: 1
										});
									}, 2000);
								}
							} else if (res.data.code == '50000') { //20240205判断组托计划锁定
							uni.hideLoading();
								uni.showToast({
									duration: 4000,
									icon: 'none',
									title: '该组托计划正在做变更已被锁定,不允许操作!'
								})
							} else {
								//隐藏加载框
								uni.hideLoading();
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 5000
								});
								return;
							}

						},
					})
				} else {
					//隐藏加载框
					uni.hideLoading();
					if (count > 0) {
						uni.showModal({
							title: '提示',
							content: '此托尚未校验完成是否临时保存？',
							success: function(res) {
								that.sumbitFlag = false;
								if (res.confirm) {
									that.setStorageSync();
								} else if (res.cancel) {
									that.removeStorageSync();
								}
								//player.stop();
								setTimeout(function() {
									uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
										delta: 1
									});
								}, 1000);
							}
						})
					} else {
						uni.showToast({
							title: '扫描的数量' + count + '与原数量' + this.detailList.length + '不一致,',
							icon: 'none',
							duration: 3000
						});
						return;
					}


				}
			},

			finished(packageId) {
				//显示加载框
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				var that = this;
				uni.request({
					url: that.baseUrl + '/system/wmsbacklog/wb2',
					data: {
						orgId: that.orgId,
						id: packageId,
						status: '3',
						userName: that.userName,
						startTime: '',
						endTime: new Date().toISOString().slice(0, 10),
					},
					method: 'POST',
					header: {
						'authorization': getToken()
					},
					dataType: 'json',
					success: (res) => {
						//隐藏加载框
						uni.hideLoading();
						if (res.data.code == '200' || res.data.code == 200) {
							uni.showToast({
								title: '组托检验成功，并且代办任务已完成',
								icon: 'none',
								duration: 3000
							});
							that.removeStorageSync();
							//that.unregisterScan();
							//player.stop();
							setTimeout(function() {
								uni.navigateBack({ //uni.navigateTo跳转的返回，默认1为返回上一级
									delta: 1
								});
							}, 1000);
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 2000
							});
							return;
						}

					},
				})
			},

			dialogConfirm(detailList) {
				for (var i = 0; i < detailList.length; i++) {
					var data = detailList[i];
					if (data.boxCode == this.boxCode) {
						if (!data.isChecked) {
							data.isChecked = true;
							break;
						}
					}
				}
			},

			print() {
				var that = this;
				var newtemplateCode = ''
				if (that.markstemplate == '' || that.markstemplate == null) {
					newtemplateCode = that.identification
				} else {
					newtemplateCode = that.markstemplate
				}
				uni.request({
					url: that.baseUrl + '/u9/printerOrder',
					data: {
						orgId: that.orgId,
						ip: that.ip + ":" + that.port,
						templateCode: newtemplateCode,
						userName: that.userName,
						panelNo: that.sn1,
						poNo: that.custPoNo,
						InvoiceNo: that.invoiceNo,
						SaleOrderNo: that.soDocno,

						qrcodeContent: that.qrcodeContent,
						printType: that.printType,
						reprint: that.reprint
					},
					method: 'POST',
					header: {
						// 'authorization':  getToken()
					},
					dataType: 'json',
					success: (res) => {
						console.log("2", res)
						//隐藏加载框
						uni.hideLoading();
						console.log('print', res.data);
						if (res.data.code == '200' || res.data.code == 200) {

						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 5000
							});
							return;
						}

					},
				})
			},

			dataConfirm() {
				var that = this;
				try {
					that.detailList = uni.getStorageSync(that.trojanCode);
					that.soDocno = uni.getStorageSync(that.trojanCode + "soDocno");
					that.sn = uni.getStorageSync(that.trojanCode + "sn");
					that.identification = uni.getStorageSync(that.trojanCode + "identification");
					that.custPoNo = uni.getStorageSync(that.trojanCode + "custPoNo");
					that.total = that.detailList.length;
					var count = 0;
					for (var i = 0; i < that.detailList.length; i++) {
						if (that.detailList[i].isChecked) {
							count = count + 1;
						}
					}
					that.scanNum = count;
					console.log(that.scanNum)
					uni.setNavigationBarTitle({
						title: that.trojanCode + '(' + that.scanNum + '/' + that.total + ')'
					});
					that.countNum();
					that.$refs.dataDialog.close();
				} catch (e) {
					console.log(e.message);
				}
			},

			dataClose() {
				var that = this;
				that.removeStorageSync();
				that.$refs.dataDialog.close();
				that.query(that.trojanCode);
			},

			removeStorageSync() {
				var that = this;
				try {
					uni.removeStorageSync(that.trojanCode);
					uni.removeStorageSync(that.trojanCode + "soDocno");
					uni.removeStorageSync(that.trojanCode + "sn");
					uni.removeStorageSync(that.trojanCode + "identification");
					uni.removeStorageSync(that.trojanCode + "custPoNo");
				} catch (e) {
					console.log(e.message);
				}
			},

			setStorageSync() {
				var that = this;
				try {
					uni.setStorageSync(that.trojanCode, that.detailList);
					uni.setStorageSync(that.trojanCode + "soDocno", that.soDocno);
					uni.setStorageSync(that.trojanCode + "sn", that.sn);
					uni.setStorageSync(that.trojanCode + "identification", that.identification);
					uni.setStorageSync(that.trojanCode + "custPoNo", that.custPoNo);
					//that.unregisterScan();

				} catch (e) {
					console.log(e.message);
				}
			},

			prompt(type) {
				var innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '/static/mp3/success.mp3';
				//innerAudioContext.play();//铃声文件的路径
				//innerAudioContext.stop();
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				innerAudioContext.onPause(function() {
					console.log('end');
					innerAudioContext.destroy()
				})
			},
		}
	}
</script>

<style lang="scss">
	.main {
		background-color: #fff;
		height: 300upx;
		align-items: center;
		margin-top: 10upx;
	}

	.text-content {
		font-size: 48rpx;
		text-align: center;
	}

	.city {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		// width: 160rpx;
		margin-left: 4px;
		font-size: 26rpx;
	}

	.input-view {
		display: flex;
		flex-direction: row;
		flex: 1;
		//background-color: #f8f8f8;
		height: 30px;
		padding: 0 80px;
		flex-wrap: nowrap;
		margin: 7px 0;
		line-height: 30px;
		font-size: 26rpx;
	}

	page {
		width: 100%;
		height: 100%;
	}


	.scrool-page {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}

	.header-cont {
		width: 100%;
		height: 110rpx;
		line-height: 100rpx;
		text-align: center;
		// background: red;
	}

	.list-cont {
		flex: 1;
		position: relative;

		.scrool-more {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}

		.list {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #e0e0e0;

		}
	}


	.footer {
		color: #fff;
		line-height: 100rpx;
		flex: 0 0 100rpx;
		/* 不放大不缩小固定100rpx */
	}
</style>